<?php

namespace app\admin\controller\crm;

use app\common\controller\Backend;
use think\Config;
use think\Cookie;
use think\Request;
use think\Session;
use Think\Db;
use app\admin\model\AuthGroup;
/**
 * B端客户跟进
 *
 * @icon fa fa-circle-o
 */
class Buserfolloe extends Backend
{
    
    /**
     * Buserfolloe模型对象
     * @var \app\admin\model\Buserfolloe
     */
    protected $model = null;
    protected  $admin_data = '';
    protected $relationSearch = true;
    protected $admin_group_id = '';//角色ID
    protected $groupidArray = array();
    public function _initialize()
    {
        parent::_initialize();
        $this->searchFields = 'id,buser.username';
        $this->model = new \app\admin\model\Buserfolloe;
        //查询当前admin权限
        $adminData = Session::get("admin");
        $linkAdmin = Db::name('Admin');
        $this->admin_data = $linkAdmin->field('a.*,g.id AS gid,g.name,g.pid')->alias('a')
            ->join('fa_auth_group_access u','a.id = u.uid','LEFT')
            ->join('fa_auth_group g','u.group_id = g.id','LEFT')
            ->where(array('a.id'=>$adminData['id']))->find();
        //判断当前用户是否是销售部人员
        $linkGroup = Db::name('auth_group');
        //查询销售部人员
        $this->di_group(13,$this->groupidArray);
        //查询所有分组
        $groupData = $linkGroup->where(array('pid'=>15,'status'=>'normal'))->select();
        $linkAdmin = Db::name('admin');
        $xiaoData = $linkAdmin->field('a.nickname,a.id')->alias('a')
            ->join('fa_auth_group_access c','a.id = c.uid','LEFT')
            ->where(array('c.group_id'=>array('IN',$this->groupidArray)))->select();
        $this->admin_group_id = $adminData['id'];
        $this->view->assign('xiaoData',$xiaoData);
        $this->view->assign('groupData',$groupData);
        $this->view->assign("sectionlistList", $this->model->getSectionlistList());
        $this->view->assign("currentlistList", $this->model->getCurrentlistList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign('admin_group_id',$this->admin_data['gid']);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看网贷客户跟进
     * $type :2：admin_id, 3:allot_id
     */
    public function index($ids='',$type=3)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $param = $this->request->param();
            $param['wf_group_id'] = isset($param['wf_group_id'])?$param['wf_group_id']:'';
            $param['wf_admin_id'] = isset($param['wf_admin_id'])?$param['wf_admin_id']:'';
            $oneWhere = array();
            if($param['wf_admin_id']){
                //查询默认销售数据
                $oneWhere['admin.id'] = $param['wf_admin_id'];
            }else if($param['wf_group_id']){
                //查询当前分组数据
                $groupArray = array();
                $this->di_group($param['wf_group_id'],$groupArray);
                if($param['wf_group_id']==12){
                    $groupArray[] = 2;
                }
                $linkAdmin = Db::name('auth_group_access');
                $adminIdArray = $linkAdmin->where(array('group_id'=>array('IN',$groupArray)))->column('uid');
                $oneWhere['admin.id'] = array('IN',$adminIdArray);
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model->alias('buserfolloe')
                    ->join('fa_allot allot','allot.id = buserfolloe.allot_id','LEFT')
                    ->join('fa_buser buser','buser.id = allot.buser_id','LEFT')
                    ->join('fa_admin admin','admin.id = allot.admin_id','LEFT')
                    ->join('fa_product product','product.id = allot.product_id','LEFT')
                    ->where($where)
                    ->where(array('allot.userlist'=>'1','buserfolloe.userlist'=>'1'))
                    ->where($oneWhere)
                    ->order($sort, $order)
                    ->count();
            /*$list = $this->model
                    ->with(['allot','admin','buser'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();*/
            $list = $this->model->alias('buserfolloe')->field('buserfolloe.`instructions`,buserfolloe.`id`,buserfolloe.`sectionimages`,
                    buserfolloe.`cooperationfiles`,buserfolloe.`sectionlist`,buserfolloe.`currentlist`,buserfolloe.`auditmsg`,
                    buserfolloe.`updatetime`,buserfolloe.`status`,buserfolloe.`adminname`,buserfolloe.`createtime`,
                    buser.`username` AS `buser.username`,buser.`qq` AS `buser.qq`,buser.`wechat` AS `buser.wechat`,
                    buser.`mobile` AS `buser.mobile` , buser.`email` AS `buser.email`,buser.`contacts` AS `buser.contacts`,
                    admin.`nickname` AS `admin.nickname`,product.`product` AS `product.product`')
                    ->join('fa_allot allot','allot.id = buserfolloe.allot_id','LEFT')
                    ->join('fa_buser buser','buser.id = allot.buser_id','LEFT')
                    ->join('fa_admin admin','admin.id = allot.admin_id','LEFT')
                    ->join('fa_product product','product.id = allot.product_id','LEFT')
                    ->where($where)
                    ->where(array('allot.userlist'=>'1','buserfolloe.userlist'=>'1'))
                    ->where($oneWhere)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
          /*  foreach ($list as $row) {
                $row->visible(['id','instructions','sectionimages','cooperationfiles','sectionlist','currentlist','auditmsg','updatetime','status','adminname','createtime']);
                $row->visible(['admin']);
                $row->getRelation('admin')->visible(['username']);
                $row->visible(['buser']);
                $row->getRelation('buser')->visible(['username','qq','wechat','mobile','email']);
            }*/
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $allotData = array('username'=>'','product'=>'');
        if($type==3&&$ids){
            //allot_id
            $linkAllot = Db::name('Allot');
            $allotData  = $linkAllot->field('b.username,p.product,a.admin_id')->alias('a')
                            ->join('fa_buser b','b.id = a.buser_id','LEFT')
                            ->join('fa_product p','p.id = a.product_id','LEFT')
                            ->where(array('a.id'=>$ids,'a.userlist'=>'1'))->find();
            $allotData = ($allotData)?$allotData:array('username'=>'','id'=>'');
            $admin_id = $allotData['admin_id'];
        }else{
            $admin_id = $ids;
        }
        $this->view->assign('allotData',$allotData);
        $this->view->assign('admin_id',$admin_id);
        return $this->view->fetch();
    }

    /**
     * 查询金融类跟进记录
     * $type :2：admin_id, 3:allot_id
     */
    public function bk_record($ids='',$type=3){
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if($this->request->isAjax()){
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $param = $this->request->param();
            $param['wf_group_id'] = isset($param['wf_group_id'])?$param['wf_group_id']:'';
            $param['wf_admin_id'] = isset($param['wf_admin_id'])?$param['wf_admin_id']:'';
            $oneWhere = array();
            if($param['wf_admin_id']){
                //查询默认销售数据
                $oneWhere['admin.id'] = $param['wf_admin_id'];
            }else if($param['wf_group_id']){
                //查询当前分组数据
                $groupArray = array();
                $this->di_group($param['wf_group_id'],$groupArray);
                if($param['wf_group_id']==12){
                    $groupArray[] = 2;
                }
                $linkAdmin = Db::name('auth_group_access');
                $adminIdArray = $linkAdmin->where(array('group_id'=>array('IN',$groupArray)))->column('uid');
                $oneWhere['admin.id'] = array('IN',$adminIdArray);
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model->with(['bkuser','admin','product','allot'])
                    ->where(array('allot.userlist'=>'2','buserfolloe.userlist'=>'2'))
                    ->where($where)
                    ->where($oneWhere)
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                    ->with(['bkuser','admin','product','allot'])
                    ->where(array('allot.userlist'=>'2','buserfolloe.userlist'=>'2'))
                    ->where($where)
                    ->where($oneWhere)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
             foreach ($list as $row) {
                  $row->visible(['instructions','cooperationfiles','sectionlist','currentlist','auditmsg','updatetime','status','adminname','createtime']);
                  $row->visible(['admin']);
                  $row->getRelation('admin')->visible(['nickname']);
                  $row->visible(['bkuser']);
                  $row->getRelation('bkuser')->visible(['company','username']);
              }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }else{
            $allotData = array('username'=>'','product'=>'');
            if($type==3&&$ids){
                //allot_id
                $linkAllot = Db::name('Allot');
                $allotData  = $linkAllot->field('b.company AS username,p.product,a.admin_id')->alias('a')
                    ->join('fa_bkuser b','b.id = a.buser_id','LEFT')
                    ->join('fa_product p','p.id = a.product_id','LEFT')
                    ->where(array('a.id'=>$ids))->find();
                $allotData = ($allotData)?$allotData:array('username'=>'','id'=>'');
                $admin_id = $allotData['admin_id'];
            }else{
                $admin_id = $ids;
            }
            $this->view->assign('allotData',$allotData);
            $this->view->assign('admin_id',$admin_id);
            return $this->view->fetch();
        }
    }
    /**
     * 跟进用户进度
     * 适用于所有类型的客户
     */
    public function add($ids=null){
        if(empty($ids)){
            $this->error('非法操作');
        }
        $allotModel = Db::name('Allot');
        $row = $allotModel->where(array('id'=>$ids))->find();
        if(!$row){
            $this->error('不存在此分配数据');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
           /* $params['buser_id'] = 0;*/
            $params['allot_id']=$ids;
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                Db::startTrans();
                try {
                    //检查B端用户是否是当前客服用户
                    if($row['userlist']==2){
                        $userData = $allotModel->field('a.id,a.status,b.id AS buser_id,a.product_id')->alias('a')
                            ->join('fa_bkuser b','b.id = a.buser_id','LEFT')
                            ->join('fa_product p','p.id = a.product_id','LEFT')
                            ->where(array('a.id'=>$ids,'a.admin_id'=>$this->admin_data['id'],'a.userlist'=>'2'))
                            ->find();
                    }else{
                        $userData = $allotModel->field('a.id,a.status,b.id AS buser_id,a.product_id')->alias('a')
                            ->join('fa_buser b','b.id = a.buser_id','LEFT')
                            ->join('fa_product p','p.id = a.product_id','LEFT')
                            ->where(array('a.id'=>$ids,'a.admin_id'=>$this->admin_data['id'],'a.userlist'=>'1'))
                            ->find();
                    }
                    if(!$userData){
                        $this->error(__('您没有分配当前B端客户'));
                    }
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['admin_id'] = $this->admin_data['id'];
                    $params['buser_id'] = $userData['buser_id'];
                    $params['product_id'] = $userData['product_id'];
                    $params['currentlist'] = ''.$userData['status'].'';
                    $params['userlist'] = ''.$row['userlist'].'';
                    //修改状态值
                    $linkAllot = Db::name('Allot');
                    $date = date('Y-m-d H:i:s',time());
                    if($params['sectionlist']==6){
                        //签约记录
                        $result = $this->model->allowField(true)->save($params);
                        //写入合作记录数据
                        $params['admin_id'] = $this->admin_data['id'];
                        $params['product_id'] = $userData['product_id'];
                        $params['admin_name'] = $this->admin_data['username'];
                        $linkCooperation = new \app\admin\model\Cooperation;
                        $cooperationAdd = $linkCooperation->allowField(true)->save($params);
                        $saveAllotField = array(
                            'status'=>$params['sectionlist'],
                            'beilist'=>'2',
                            'typelist'=>'2',
                            'qilist'=>'1',
                            'followuptime'=>$date,
                            'expire_date'=>'0000-00-00 00:00:00',
                            'nexttime'=>'0000-00-00 00:00:00'
                        );
                        $sectionlist =  $linkAllot->where(array('id'=>$ids))->update($saveAllotField);
                        if ($result !== false&&$cooperationAdd !== false&&$sectionlist) {
                            Db::commit();
                            $this->success();
                        } else {
                            Db::rollback();
                            $this->error($this->model->getError());
                        }
                    }else{
                        $result = $this->model->allowField(true)->save($params);
                        $allotField = array(
                            'status'=>''.$params['sectionlist'].'',
                            'followuptime'=>$date,
                            'nexttime'=>$params['nexttime']
                        );
                        $save =  $linkAllot->where(array('id'=>$ids))->update($allotField);
                        //其它跟进状态
                        if($result&&$save){
                            Db::commit();
                            $this->success();
                        }else{
                            Db::rollback();
                            $this->error($this->model->getError());
                        }
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            //查询B端用户数据
            $buserWhere = array('a.admin_id'=>$this->admin_data['id'],'a.id'=>$ids);
            if($row['userlist']==2){
                //金融类客户
                $buserData = $allotModel->field('a.id,b.company AS username,a.status,p.product')
                            ->alias('a')->join('fa_bkuser b ',' b.id = a.buser_id ',' LEFT ')
                            ->join('fa_product p','p.id = a.product_id','LEFT')
                            ->where($buserWhere)
                            ->find();
            }else{
                $buserData = $allotModel->field('a.id,b.username,a.status,p.product')
                    ->alias('a')->join('fa_buser b ',' b.id = a.buser_id ',' LEFT ')
                    ->join('fa_product p','p.id = a.product_id','LEFT')
                    ->where($buserWhere)
                    ->find();
            }
            if($buserData['status']==0){
                $status='无意向用户';
            }else if($buserData['status']==1){
                $status='意向用户';
            }else if($buserData['status']==2){
                $status = '谈合作';
            }else if($buserData['status']==3){
                $status = '我方盖章';
            }else if($buserData['status']==4){
                $status = '对方盖章';
            }else if($buserData['status']==5){
                $status = '待付款';
            }
            $name = '客户:'.$buserData['username'].' - 状态:'.$status.' - 产品:'.$buserData['product'].'';
            $buserData['info'] = $name;
            $this->view->assign('buserData',$buserData);
            $this->view->assign('ids',$ids);
            $this->view->assign('userlist',$row['userlist']);
            return $this->view->fetch();
        }
    }

    /**
     * 查询当前客服下客户数据
     * $userlist
     */
/*    public function allot_user($userlist=1){
            $username = $this->request->param('username');
            $searchValue = $this->request->param('searchValue');//编辑页面默认选中的参数
            $linkAllot = Db::name('Allot');
            $where = array(
                'a.admin_id'=>$this->admin_data['id'],
                'a.status'=>array('NOT IN','6')
            );
            if($username){
                $where['b.username'] = array('LIKE','%'.$username.'%');
            }
            if($searchValue){
                $where['a.id'] = $searchValue;
            }
            if($userlist==2){
                //金融类客户
                $allotData = $linkAllot->field('b.company AS username,a.id,a.status,p.product AS pname')
                            ->alias('a')->join('fa_bkuser b','a.buser_id = b.id','LEFT')
                            ->join('fa_product p','a.product_id = p.id','LEFT')
                            ->where($where)->where(array('a.userlist'=>2))->select();
            }else{
                //网贷客户
                $allotData = $linkAllot->field('b.username,a.id,a.status,p.product AS pname')
                    ->alias('a')->join('fa_buser b','b.id = a.buser_id','LEFT')
                    ->join('fa_product p','a.product_id = p.id','LEFT')
                    ->where($where)->where(array('a.userlist'=>1))->select();
            }
            $list = collection($allotData)->toArray();
            foreach ($list as $k=>$v){
                if($v['status']==0){
                    $status='无意向用户';
                }else if($v['status']==1){
                    $status='意向用户';
                }else if($v['status']==2){
                    $status = '谈合作';
                }else if($v['status']==3){
                    $status = '我方盖章';
                }else if($v['status']==4){
                    $status = '对方盖章';
                }else if($v['status']==5){
                    $status = '待付款';
                }
                $name = '客户:"'.$v['username'].'" - 状态:"'.$status.'" - 产品:"'.$v['pname'].'"';
                $list[$k]['username'] = $name;
            }
            $result = array("rows" => $list);
            return json($result);
    }*/
}
